package com.benson.common.creator.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.benson.common.creator.dto.CreatorSaveDto;
import com.benson.common.creator.entity.Creator;
import com.benson.common.creator.entity.Pagination;
import com.benson.common.creator.entity.ResultPoJo;
import com.benson.common.creator.entity.enums.TypeFileEnum;
import com.benson.common.creator.service.ICreatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 代码生成 前端控制器
 * </p>
 *
 * @author zhangby
 * @since 2020-02-18
 */
@RestController
@RequestMapping("/api/creator")
public class CreatorController {

    @Autowired
    ICreatorService creatorService;

    /**
     * 获取创建记录
     *
     * @return
     */
    @GetMapping("")
    public ResultPoJo<IPage<Creator>> getCreatorList(Pagination pagination, String keyword) {
        LambdaQueryWrapper<Creator> queryWrapper = new LambdaQueryWrapper<Creator>()
                .orderByDesc(Creator::getCreateDate);
        // 模糊查询
        Optional.ofNullable(keyword)
                .filter(StrUtil::isNotBlank)
                .ifPresent(key -> {
                    queryWrapper.and(andQw ->
                            andQw.or(orQw -> orQw.like(Creator::getName, key))
                                    .or(orQw -> orQw.like(Creator::getTableName, key))
                                    .or(orQw -> orQw.like(Creator::getAuthor, key))
                                    .or(orQw -> orQw.like(Creator::getOutPutDir, key))
                                    .or(orQw -> orQw.like(Creator::getPackageDir, key))
                    );
                });
        IPage page = creatorService.page(pagination.page(),queryWrapper);
        return ResultPoJo.ok(page);
    }

    /**
     * 获取生成记录
     *
     * @return
     */
    @GetMapping("/{id}")
    public ResultPoJo<Creator> getCreatorById(@PathVariable String id) {
        Creator creator = creatorService.getById(id);
        return ResultPoJo.ok(creator);
    }

    /**
     * 获取代码生成类型
     *
     * @return
     */
    @GetMapping("/file/type/data")
    public ResultPoJo<List<Dict>> getFileTypeData() {
        List<Dict> list = Stream.of(TypeFileEnum.values())
                .map(en -> Dict.create()
                        .set("label", en.getLabel())
                        .set("value", en.getValue())
                )
                .collect(Collectors.toList());
        return ResultPoJo.ok(Dict.create()
                .set("label", "代码生成类型")
                .set("value", "0")
                .set("children", list)
        );
    }

    /**
     * 保存代码生成
     *
     * @return
     */
    @PostMapping("")
    public ResultPoJo saveCreator(@Validated @RequestBody CreatorSaveDto creatorSaveDto) {
        Creator creator = creatorSaveDto.convert()
                .setId(IdUtil.simpleUUID())
                .setCreateDate(new Date())
                .setUpdateDate(new Date());
        creatorService.save(creator);
        return ResultPoJo.ok();
    }

    /**
     * 更新代码生成
     *
     * @return
     */
    @PutMapping("/{id}")
    public ResultPoJo updateCreator(@PathVariable String id, @Validated @RequestBody CreatorSaveDto creatorSaveDto) {
        Creator creator = creatorSaveDto.convert()
                .setId(id)
                .setUpdateDate(new Date());
        creatorService.updateById(creator);
        return ResultPoJo.ok();
    }

    /**
     * 删除
     *
     * @return
     */
    @DeleteMapping("/{id}")
    public ResultPoJo deleteCreator(@PathVariable String id) {
        creatorService.removeByIds(CollectionUtil.newArrayList(id.split(",")));
        return ResultPoJo.ok();
    }

    /**
     * 代码生成
     *
     * @return
     */
    @PostMapping("/generator/{id}")
    public ResultPoJo generator(@PathVariable String id) {
        try {
            for (String cId : id.split(",")) {
                creatorService.generator(cId);
            }
            return ResultPoJo.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultPoJo()
                    .setCode("999")
                    .setMsg("代码生成失败，请检查生成配置");
        }
    }
}

